import { t } from 'i18next'
import {
	DepartmentUser,
	getItemInPending,
	makeSelectedMtModelListTranslator,
	PendingItem,
	pendingModelTranslator,
	PendingMtModel,
	pendingTemplateListTranslator,
	selectedMtEntityTranslator,
	SelectedMtModel,
	SelectMtEntity,
	Template,
	TreeNode,
} from './translator'
import { MtEntity, MtItem } from './interface'
import { IStore, useMtAddStore } from './store'
import { usePendingStore as pendingStore } from './blocks/pending/store'
import { useSelectedStore as selectedStore } from './blocks/selected/store'
import { fetchTemplatesSearch, fetchUser } from '@/api/addMt'
import { useMccStore } from '@/pages/manager/store'
import { CONSTANT } from './utils/utils'
import { useTableInteractiveStore } from '@/pages/manager/blocks/main/table/interactive/store'
import { getItemInTree } from '@/pages/manager/blocks/main/table/all/utils'
import { useTableAllStore } from '@/pages/manager/blocks/main/table/all/store'
import { fetchCallMt } from '@/api/manager/actions'

import { confirmModal } from '../Alert'
import { useRollCallStore } from '@/pages/manager/blocks/roll/store'

export const itemAddToRight = (
	data: PendingItem<DepartmentUser | Template>,
	callType: 'video' | 'audio' | 'phone' | 'auto'
) => {
	const { isMcc, isSuperMeeting, maxRate } = useMtAddStore.getState()
	const addItem = selectedStore.getState().addItem
	const removeItemSelected = pendingStore.getState().removeItemSelected
	const item = selectedMtEntityTranslator(data, callType, { isMcc, isSuperMeeting, maxRate })
	addItem(new SelectedMtModel(item))
	removeItemSelected(data)
}
export const addSelectedToRight = () => {
	const { isMcc, isSuperMeeting, maxRate } = useMtAddStore.getState()
	const tree = pendingStore.getState().tree
	const removeAllSelected = pendingStore.getState().removeAllSelected
	const addList = selectedStore.getState().addList
	let selectedUsers: PendingMtModel<DepartmentUser>[] = []
	let selectedTemplates: PendingMtModel<Template>[] = []
	getItemInPending(tree, (data) => {
		const r = data.users.filter((x) => x.status.isSelected)
		if (data.item.type === 'group' || data.item.type === 'org') {
			selectedUsers = [...selectedUsers, ...(r as PendingMtModel<DepartmentUser>[])]
		} else if (data.item.type === 'template') {
			selectedTemplates = [...selectedTemplates, ...(r as PendingMtModel<Template>[])]
		}
	})
	const resultList = makeSelectedMtModelListTranslator(
		{ selectedUsers, selectedTemplates },
		{ isMcc, isSuperMeeting, maxRate }
	)
	addList(resultList)
	removeAllSelected()
}
export const addAllSelectedToRight = async () => {
	const { isMcc, isSuperMeeting, maxRate } = useMtAddStore.getState()
	const tree = pendingStore.getState().tree
	const removeAllSelected = pendingStore.getState().removeAllSelected
	const searchType = pendingStore.getState().searchType
	const addList = selectedStore.getState().addList
	let selectedTreeNodes: PendingMtModel<TreeNode>[] = []
	let selectedUsers: PendingMtModel<DepartmentUser>[] = []
	let selectedTemplates: PendingMtModel<Template>[] = []
	getItemInPending(tree, (data) => {
		if (data.status.isSelected) {
			selectedTreeNodes.push(data)
			return 'continue'
		} else {
			const r = data.users.filter((x) => x.status.isSelected)
			if (data.item.type === 'group' || data.item.type === 'org') {
				selectedUsers = [...selectedUsers, ...(r as PendingMtModel<DepartmentUser>[])]
			} else if (data.item.type === 'template') {
				selectedTemplates = [...selectedTemplates, ...(r as PendingMtModel<Template>[])]
			}
		}
	})
	//处理选择的 treeNode
	if (searchType !== null) {
		//不用请求，直接取
		getItemInPending(selectedTreeNodes, (data) => {
			if (data.item.type === 'group' || data.item.type === 'org') {
				selectedUsers = [...selectedUsers, ...(data.users as PendingMtModel<DepartmentUser>[])]
			} else if (data.item.type === 'template') {
				selectedTemplates = [...selectedTemplates, ...(data.users as PendingMtModel<Template>[])]
			}
		})
	} else {
		//需请求获取部门下的所有人
		const promiseRes = selectedTreeNodes.map(async (treeNode) => {
			if (treeNode.item.type === 'group') {
				let _temp = treeNode.id.split('_')
				const res = await fetchUser({
					public_group_moid: _temp.length === 2 ? _temp[1] : _temp[0],
					is_all: true,
				})
				if (res) {
					const { users } = res
					const userModel = users.map((x) => pendingModelTranslator(new DepartmentUser(x)))
					return { selectedUsers: userModel }
				}
			} else if (treeNode.item.type === 'org') {
				let _temp = treeNode.id.split('_')
				const res = await fetchUser({
					department_moid: _temp.length === 2 ? _temp[1] : '',
					user_domain_moid: _temp[0],
					is_all: true,
				})
				if (res) {
					const { users } = res
					const userModel = users.map((x) => pendingModelTranslator(new DepartmentUser(x)))
					return { selectedUsers: userModel }
				}
			} else if (treeNode.item.type === 'template') {
				const res = await fetchTemplatesSearch('')
				if (res && res.list) {
					const templateModel = pendingTemplateListTranslator(res.list)
					return { selectedTemplates: templateModel }
				}
			}
		})
		for (const res of promiseRes) {
			const data = await res
			if (data) {
				if (data.selectedUsers) selectedUsers = [...selectedUsers, ...data.selectedUsers]
				if (data.selectedTemplates) selectedTemplates = [...selectedTemplates, ...data.selectedTemplates]
			}
		}
	}
	const resultList = makeSelectedMtModelListTranslator(
		{ selectedUsers, selectedTemplates },
		{ isMcc, isSuperMeeting, maxRate }
	)
	addList(resultList)
	removeAllSelected()
}
export function resetAllStore() {
	selectedStore.getState().reset()
	pendingStore.getState().reset()
	useMtAddStore.getState().reset()
}
export function init(params: Partial<IStore> & { selectedEntityMts: SelectMtEntity[] }) {
	const { selectedEntityMts = [], isMcc, mccModel, ...state } = params
	selectedStore.getState().initSelectedList(selectedEntityMts)
	useMtAddStore.setState(state)
	if (isMcc && mccModel) {
		console.log('mccModel', mccModel)
		useMtAddStore.getState().initMcc(mccModel)
	}
}
export function mccAddMt(mts: SelectMtEntity[], smcuMtid: string, isSub?: boolean) {
	const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
	const superMtNum = useMccStore.getState().mccInfo.superMtNum
	const isCascade = useMtAddStore.getState().isCascade
	const mtArray: Array<MtItem> = []
	let mtItem: MtItem = {}
	/**
	 * 构造数据结构, 注：这块后台没有做任何处理，导致和创会不一样，需要前台直接下对应的给cmu
	 * 此时 accountType 1 代表 e164 呼叫
	 */
	// mts.map((mt) => {
	for (let i = 0, len = mts.length; i < len; i++) {
		mtItem = {}
		let mt = mts[i]
		mtItem.name = mt.name || ''
		mtItem.account = mt.account || ''
		mtItem.bitrate = isSub ? useMccStore.getState().mccInfo.meetingRate : mt.bitrate || 0
		mtItem.meetingMoid = meetingMoid || ''
		mtItem.accountType = mt.accountType || 0
		mtItem.protocol = isSub ? 255 : mt.protocol || 0
		if (superMtNum) {
			mtItem.interactiveMt = isSub ? 1 : mt.interactiveMt
		} else {
			mtItem.oftenMt = mt.oftenMt
		}
		//允许邻居gk类型的设备呼入
		if (mtItem.accountType === CONSTANT.accountType.softTerminal) {
			//本质为没e164 不下参 （组件内部存在account=moid）
			if (!mt.e164 && mt.account === mt.moid) {
				continue
			}
		}
		if (mtItem.accountType === CONSTANT.accountType.softTerminal) {
			mtItem.account = mt.e164?.trim()
			mtItem.accountType = 5
		}
		mtArray.push(mtItem)
	}
	if (mtArray.length === 0) {
		!isSub && resetAllStore()
		return
	}
	function addMTInner() {
		function parseParams() {
			let newArr = mtArray.map((item) => ({
				name: item.name,
				account: item.account,
				account_type: item.accountType,
				protocol: item.protocol,
				often_mt: item.oftenMt,
				interactive_mt: item.interactiveMt,
				bitrate: item.bitrate,
			}))
			return {
				cascade_id: isSub && useMccStore.getState().mccInfo.smartCascadeMode !== 0 ? '' : smcuMtid,
				mts: newArr,
			}
		}
		function doCall(data: { smcuMtid?: string; mtList: MtItem[] }) {
			// !isSub && window.TS.mcc.rollCall.addMts(data)
			!isSub && useRollCallStore.getState().addMts({ smcumtid: data.smcuMtid, mtList: data.mtList as MtEntity[] })
			let callParam = parseParams()
			console.log('callParam', callParam)
			fetchCallMt(meetingMoid, callParam)
		}
		if (isCascade) {
			if (smcuMtid) {
				doCall({
					smcuMtid,
					mtList: mtArray,
				})
			} else {
				doCall({ mtList: mtArray })
			}
		} else {
			doCall({ mtList: mtArray })
		}
		!isSub && resetAllStore()
	}
	if (isCascade && smcuMtid) {
		if (smcuMtid == '0.0.0.0_0') {
			if (isInScale(mtArray)) {
				//没有超过会议规模
				addMTInner()
			} else {
				//超过会议规模
				showOverScaleDialog(addMTInner)
			}
		} else {
			addMTInner()
		}
	} else {
		if (isInScale(mtArray)) {
			//没有超过会议规模
			addMTInner()
		} else {
			//超过会议规模
			showOverScaleDialog(addMTInner)
		}
	}
}
/** 是否在会议规模内 */
const isInScale = (mtList: Array<MtItem>) => {
	//判断是否在会议规模范围内
	/*
	变量定义 let
	获得store的数据 const
	*/
	let cashLength = 0
	let len = 0
	const superMtNum = useMccStore.getState().mccInfo.superMtNum
	if (superMtNum) {
		cashLength = useTableInteractiveStore.getState().list.length
		len = cashLength + mtList.filter((mt) => mt.interactiveMt).length
	} else {
		const tree = useTableAllStore.getState().tree
		getItemInTree(tree, (item) => {
			if (item.mcc.confLevel === 2 && item.mtKey !== '0.0.0.0_0') {
				cashLength++
			}
		})
		// TS.mcc.main.getItemInTree(({ mcc: item }) => {
		// 	if (item.confLevel === 2 && item.mtKey !== '0.0.0.0_0') {
		// 		cashLength++
		// 	}
		// })
		len = cashLength + mtList.length
	}
	let scale = getMeetingScaleNum()
	if (scale === 192) {
		scale = 190
	}
	if (scale) {
		if (len > scale) {
			//超过会议规模
			return false
		} else {
			//没有超过会议规模
			return true
		}
	}
	return true //没有会议规模字段
}
const getMeetingScaleNum = () => {
	return useMccStore.getState().mccInfo.meetingResourceVO.multi || 192
}
const showOverScaleDialog = (callback: Function) => {
	confirmModal({
		msg: (
			<div>
				{t('邀请的与会方数量已超过当前会议规模')}，
				<br />
				{t('部分终端可能呼叫失败')}
			</div>
		),
		onOk: () => callback(),
		okText: t('继续邀请'),
		cancelText: t('返回修改'),
	})
}
